<template>
  <el-card class="chart-card">
    <h3 class="chart-title">{{ hotVoteTop.voteTitle }}</h3>
    <div class="chart-container">
      <canvas ref="pieChartRef"></canvas>
    </div>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { Chart, registerables } from 'chart.js';
import { getVoteOptionRatio,hotVoteTop1 } from '@/api/business/dashboard';


Chart.register(...registerables);
const pieChartRef = ref(null);
let chartInstance = null;
const hotVoteTop = ref({});

onMounted(async () => {
  const res = await getVoteOptionRatio();
  const data = res.data;
  const labels = data.map(item => item.optionName);
  const percentages = data.map(item => item.percentage);
  const colors = data.map(item => item.color);

  chartInstance = new Chart(pieChartRef.value, {
    type: 'pie',
    data: { labels, datasets: [{ data: percentages, backgroundColor: colors, borderWidth: 0 }] },
    options: {
      responsive: true,
      maintainAspectRatio: false,
      plugins: {
        legend: { position: 'right' },
        tooltip: {
          callbacks: {
            label: (ctx) => {
              const item = data[ctx.dataIndex];
              return `${item.optionName}：${item.votes} 票 (${item.percentage}%)`;
            }
          }
        }
      }
    }
  });
    hotVoteTop1().then((response) => {
    hotVoteTop.value = response.data;
  });
});
</script>

<style scoped>
.chart-card { height: 300px; padding: 15px; position: relative; }
.detail-btn { position: absolute; bottom: 15px; right: 20px; }
.blue-btn { color: #165DFF; padding: 0; }
.chart-container {width: 100%; height: 200px; }
.chart-title { font-size: 16px; color: #333; margin-bottom: 10px; }
</style>